/**
 * 
 * EXERCISE 1
 * 
 * @param {*} promise 
 * @param {*} transformer 
 * @returns {Promise}
 */
function mapPromise(promise, transformer){
  return new Promise((resolve, reject) => {
    /* IMPLEMENT ME!! */
    promise.then(res => {
      return transformer(res);
    }).then(res => {
      resolve(res);
    }).catch(err => { 
      reject(err);
    });
  });
}

/**
 * 
 * EXERCISE 2
 * 
 * @param {Promise<number | string>} numberPromise 
 * @returns {Promise<number>}
 */
function squarePromise(numberPromise){
  return numberPromise
    .then(
      /* IMPLEMENT ME! */
      res => {
        // TODO: 这种情况不行
        // let num = Number(res);
        // if (isNaN(num)) {
        //   throw new Error('Cannot convert \'abc\' to a number!');
        // } else {
        //   return (num * num);
        // }

        // 这种可以。
        // return new Promise((resolve, reject) => {
        //   let num = Number(res);
        //   if (isNaN(num)) {
        //     reject('Cannot convert \'abc\' to a number!');
        //   } else {
        //     resolve(num * num);
        //   }
        // });

        let num = Number(res);
        if (isNaN(num)) {
          return Promise.reject('Cannot convert \'abc\' to a number!');
        } else {
          return Promise.resolve(num * num);
        }
      }
    );
}

/**
 * EXERCISE 3
 * 
 * @param {Promise<number | string>} numberPromise 
 * @returns {Promise<number>}
 */
function squarePromiseOrZero(promise){
  return squarePromise(promise)
    .catch(
      /* IMPLEMENT ME! */
      err => {
        return Promise.resolve(0);
      }
    );
}

/**
 * EXERCISE 4
 * 
 * @param {Promise} promise 
 * @returns {Promise}
 */
function switcheroo(promise){
  return promise.then(
    /* IMPLEMENT ME */
    res => {
      return Promise.reject(res);
    },
    reject => {
      return Promise.resolve(reject);
    }
  );
}

/**
 * @callback consumer
 * @param {*} value
 */

/**
 * @callback handler
 * @param {*} error
 */

module.exports = {
  mapPromise,
  squarePromise,
  squarePromiseOrZero,
  switcheroo,
};